<!-- 用户管理 -->
<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="昵称/手机号" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable class="!w-[100px]">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker v-model="queryParams.createTime" :editable="false" class="!w-[240px]" type="daterange"
            range-separator="~" start-placeholder="开始时间" end-placeholder="截止时间" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="flex flex-col h-full" body-style="height: calc(100% - 0px);">
      <!-- <div class="flex-x-between mb-10px">
            <div>
              <el-button v-hasPerm="['sys:user:add']" type="success" icon="plus" @click="handleOpenDialog()">
                新增
              </el-button>
              <el-button v-hasPerm="'sys:user:delete'" type="danger" icon="delete" :disabled="selectIds.length === 0"
                @click="handleDelete()">
                删除
              </el-button>
            </div>
            <div>
              <el-button v-hasPerm="'sys:user:import'" icon="upload" @click="handleOpenImportDialog">
                导入
              </el-button>

              <el-button v-hasPerm="'sys:user:export'" icon="download" @click="handleExport">
                导出
              </el-button>
            </div>
          </div> -->
      <BasePageTable :tableColumnsData="columns" :tableData="pageData" :pageSize="queryParams.pageSize"
        :pageNum="queryParams.pageNum" :total="total" :loading="loading" class="h-full" @handleQuery="changePage">
        <template #gender="scope">
          <!-- 性别字典翻译 -->
          <el-tag :type="scope.row.gender == 1 ? 'success' : 'warning'">
            {{ scope.row.gender == 1 ? "男" : "女" }}
          </el-tag>
        </template>
        <template #roleNames="scope">
          <el-tag>
            {{ scope.row.roleNames }}
          </el-tag>
        </template>
        <template #partnerText="{ row }">
          <span>
            {{ getPartnerText(row) }}
          </span>
        </template>
        <template #floatCommissionRatio="{ row }">
          {{ getRatio(row) }}
        </template>
        <template #userType="scope">
          <el-tag>{{ SYSTEM_TYPE_OBJECT[scope.row.userType] }}</el-tag>
        </template>
        <template #status="scope">
          <el-switch v-model="scope.row.status" inline-prompt active-text="正常" inactive-text="禁用" :active-value="1"
            :inactive-value="0" :before-change="() => handleStatusChange(scope.row.id, scope.row.status)" />
          <!-- <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
                {{ scope.row.status == 1 ? "正常" : "禁用" }}
              </el-tag> -->
        </template>

        <template #operation="scope">
          <!-- <el-switch v-model="scope.row.status" inline-prompt active-text="正常" inactive-text="禁用" :active-value="1"
                :inactive-value="0" />
              <el-button v-hasPerm="'sys:user:password:reset'" type="primary" icon="RefreshLeft" size="small" link
                @click="hancleResetPassword(scope.row)">
                重置密码
              </el-button> -->
          <!-- <el-button v-hasPerm="'sys:user:edit'" type="primary" icon="edit" link size="small"
            :disabled="!isDisabled(scope.row.userType)" @click="handleOpenDialog(scope.row)">
            绑定B端合伙人
          </el-button> -->
          <!--          <el-button v-hasPerm="'sys:user:edit'" type="primary" icon="edit" link size="small"-->
          <!--            :disabled="isDisabledCommissionRatio(scope.row.userType)" @click="handleClickCommissionRatio(scope.row)">-->
          <!--            设置浮动佣金比例-->
          <!--          </el-button>-->
          <!-- <el-button
            v-hasPerm="'sys:user:delete'"
            type="danger"
            icon="delete"
            link
            size="small"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button> -->
          <el-button link type="primary" icon="ChatDotSquare" @click="handleGreet(scope.row)">
            聊天
          </el-button>
        </template>
      </BasePageTable>
    </el-card>
    <!-- 用户表单 -->
    <el-drawer v-model="dialog.visible" :title="dialog.title" append-to-body @close="handleCloseDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100">
        <el-form-item label="高级合伙人" prop="partnerId">
          <el-select v-model="formData.partnerId" placeholder="请选择高级合伙人">
            <el-option v-for="item in usersOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 用户导入 -->
    <!-- <UserImport v-model="importDialogVisible" @import-success="handleQuery()" /> -->
    <commission-ratio-form ref="commissionRatioFormRef" @load-data="handleQuery"></commission-ratio-form>
  </div>
</template>

<script setup lang="ts">
import { SYSTEM_TYPE_OBJECT } from "@/utils/enums/system";
import UserAPI, { UserForm, UserPageQuery, UserPageVO } from "@/api/system/user";
import MerchantUserAPI from "@/api/user/merchantuser";
import BasePageTable from "@/components/BasePageTable/index.vue";
import { USER_TYPE_ENUM, UserTypeEnum } from "@/enums/user/UserEnum";
import { getLabelValueList } from "@/utils/enums";
import ConsumerUserAPI, { MerchantBPartnerForm } from "@/api/user/consumeruser";
import { useNimStore } from "@/store/modules/nim.js";
const { sendMessage } = useNimStore();
import router from "@/router/index.js";
import { V2NIMConst } from "nim-web-sdk-ng";
import CommissionRatioForm from "@/views/user/merchantUser/components/commission-ratio-form.vue";

defineOptions({
  name: "User",
  inheritAttrs: false,
});
const usersOptions = ref([]);
const commissionRatioFormRef = ref();
const columns = ref<any[]>([
  // {
  //   label: "用户名",
  //   prop: "username",
  //   width: 200,
  //   align: "center",
  //   showOverflowTooltip: true,
  // },
  {
    label: "序号",
    prop: "index",
    align: "center",
    width: 60,
    showOverflowTooltip: true,
  },
  {
    label: "昵称",
    prop: "nickname",
    align: "center",
    showOverflowTooltip: true,
  },
  {
    label: "手机号码",
    prop: "mobile",
    align: "center",
    showOverflowTooltip: true,
  },
  // {
  //   label: "角色",
  //   prop: "roleNames",
  //   align: "center",
  //   showOverflowTooltip: true,
  //   customSlot: "roleNames", // 自定义插槽名称
  // },
  {
    label: "公司别名",
    prop: "companyAlias",
    align: "center",
    showOverflowTooltip: true,
  },
  {
    label: "公司名称",
    prop: "companyName",
    align: "center",
    showOverflowTooltip: true,
  },
  {
    label: "合伙人名称",
    prop: "merchantCompanyVO.mallName",
    align: "center",
    showOverflowTooltip: true,
  },
  {
    label: "佣金比例",
    prop: "merchantCompanyVO.mallCommission",
    align: "center",
    showOverflowTooltip: true,
    formatter: (row, column, cellValue) => {
      if (cellValue === null || cellValue === undefined) return '-'
      return `${(cellValue * 100).toFixed(2)}%`
    }
  },
  {
    label: "用户类型",
    prop: "userType",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "userType", // 自定义插槽名称
  },
  // {
  //   label: "高级合伙人",
  //   customSlot: "partnerText",
  //   align: "center",
  //   showOverflowTooltip: true,
  // },
  // {
  //   label: "浮动佣金比例",
  //   prop: "merchantCompanyVO.floatCommissionRatio",
  //   align: "center",
  //   customSlot: "floatCommissionRatio",
  //   showOverflowTooltip: true,
  // },
  {
    label: "状态",
    prop: "status",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "status", // 自定义插槽名称
  },
  {
    label: "创建时间",
    prop: "createTime",
    align: "center",
    showOverflowTooltip: true,
  },
  // {
  //   label: "操作",
  //   prop: "operation",
  //   width: 150,
  //   align: "center",
  //   fixed: "right",
  //   showOverflowTooltip: true,
  //   customSlot: "operation", // 自定义插槽名称
  // },
]);
const queryFormRef = ref();
const userFormRef = ref();

const queryParams = reactive<UserPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<UserPageVO[]>();
const total = ref(0);
const loading = ref(false);
const handleStatusChange = (value: number, status: number) => {
  try {
    MerchantUserAPI.updateStatus(value, status === 1 ? 0 : 1).then(() => {
      ElMessage.success("状态更新成功");
      initData();
    });
    return true;
  } catch (error) {
    console.log(error);
    ElMessage.error("状态更新失败");
    return false;
  }
};
const dialog = reactive({
  visible: false,
  title: "新增用户",
});

const formData = ref<MerchantBPartnerForm>({
  userType: "",
  partnerId: undefined,
});

const rules = reactive({
  partnerId: [{ required: true, message: "请选择高级合伙人", trigger: "change" }],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
// 角色下拉数据源
const roleOptions = ref<OptionType[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 查询
function handleQuery() {
  loading.value = true;
  MerchantUserAPI.getList(queryParams)
    .then((data: any): any => {
      pageData.value = data.data.map((item: any, index: number) => ({
        ...item,
        index: index + 1,
        companyName: item?.merchantCompanyVO?.companyName || "",
        companyAlias: item?.merchantCompanyVO?.companyAlias || "",
        bPartnerBySelf: item?.merchantCompanyVO?.bPartnerBySelf || "",
        bPartnerBySenior: item?.merchantCompanyVO?.bPartnerBySenior || "",
      }));
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
function changePage(val: any) {
  queryParams.pageNum = val.pageNum;
  queryParams.pageSize = val.pageSize;
  handleQuery();
}

// 重置查询
function handleResetQuery() {
  queryParams.pageNum = 1;
  initData();
}
function initData() {
  queryFormRef.value.resetFields();
  // queryParams.deptId = undefined;
  queryParams.createTime = undefined;
  handleQuery();
}
// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

// 重置密码
function hancleResetPassword(row: UserPageVO) {
  ElMessageBox.prompt("请输入用户【" + row.username + "】的新密码", "重置密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(
    ({ value }) => {
      if (!value || value.length < 6) {
        ElMessage.warning("密码至少需要6位字符，请重新输入");
        return false;
      }
      UserAPI.resetPassword(row.id, value).then(() => {
        ElMessage.success("密码重置成功，新密码是：" + value);
      });
    },
    () => {
      ElMessage.info("已取消重置密码");
    }
  );
}

function getRatio(row) {
  if (row.merchantCompanyVO?.floatCommissionRatio) {
    return (Number(row.merchantCompanyVO.floatCommissionRatio) * 100).toFixed(2) + "%";
  } else {
    return "";
  }
}

async function handleOpenDialog(val) {
  getUsersOptions();
  dialog.visible = true;
  const { userType, merchantCompanyVO, merchantEmployeeVO } = val;
  formData.value.userType = userType;
  if (
    userType === UserTypeEnum.DECORATION_COMPANY.value ||
    userType === UserTypeEnum.HOME_BUILDING_MATERIALS.value
  ) {
    formData.value.companyId = merchantCompanyVO?.id;
    formData.value.partnerId = String(merchantCompanyVO?.partnerId);
  } else if (userType === UserTypeEnum.DESIGNER.value) {
    formData.value.merchantUserId = merchantEmployeeVO?.merchantUserId;
    formData.value.partnerId = String(merchantEmployeeVO?.partnerId);
  }
}

/**
 * 设计师 项目经理 不支持配置
 * @param val
 */
async function handleClickCommissionRatio(val) {
  commissionRatioFormRef.value.showModal(val);
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      ConsumerUserAPI.updateBPartner(formData.value)
        .then(() => {
          ElMessage.success("成功");
          handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 1000);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      UserAPI.deleteByIds(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

// 导出用户
function handleExport() {
  UserAPI.export(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(response.headers["content-disposition"].split(";")[1].split("=")[1]);
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

function isDisabled(userType) {
  ////装修公司 设计师  建材商 才可以编辑
  return [
    UserTypeEnum.DECORATION_COMPANY.value,
    UserTypeEnum.HOME_BUILDING_MATERIALS.value,
    UserTypeEnum.DESIGNER.value,
  ].includes(userType);
}
function isDisabledCommissionRatio(userType) {
  return [UserTypeEnum.DESIGNER.value, UserTypeEnum.PROJECT_MANAGER.value].includes(userType);
}

async function getUsersOptions() {
  try {
    const data = await MerchantUserAPI.getUsersOptions({
      types: `${USER_TYPE_ENUM.SENIOR_PARTNER.value},${USER_TYPE_ENUM.CHANNEL_PARTNER.value}`,
    });
    usersOptions.value = data.data;
  } catch (e) {
    console.log(e);
  } finally {
  }
}

function getPartnerText(val) {
  const { userType, merchantCompanyVO, merchantEmployeeVO } = val;
  if (
    userType === UserTypeEnum.DECORATION_COMPANY.value ||
    userType === UserTypeEnum.HOME_BUILDING_MATERIALS.value
  ) {
    return merchantCompanyVO?.partnerText;
  } else {
    return merchantEmployeeVO?.partnerText;
  }
}

async function handleGreet(val) {
  try {
    const { accountId } = val.merchantIm || {};
    if (!accountId) {
      return ElMessage.error("该用户暂未绑定IM账号");
    }
    await sendMessage(
      "你好，在吗？",
      accountId,
      V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_P2P
    );
    router.push({
      path: "/chatList",
    });
  } catch (e) {
    console.log(e);
    ElMessage.error("聊天失败");
  }
}

onMounted(() => {
  getUsersOptions();
  handleQuery();
});
</script>
